package org.example.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.domain.SysUserRole;
import org.example.mapper.SysUserRoleMapper;
import org.example.service.SysUserRoleService;
import org.example.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mapper.SysUserMapper;
import org.example.domain.SysUser;
import org.example.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    @Transactional(noRollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(AuthUtils.getLoginUser().getShopId());
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        int i = sysUserMapper.insert(sysUser);
        if(i>0){
            //获取刚新增的用户id
            Long userId = sysUser.getUserId();
            // 添加用户角色关系
            List<Long> roleIdList = sysUser.getRoleIdList();
            if(CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size()!=0){
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);

                    sysUserRoleList.add(sysUserRole);
                });
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }

        return i;
    }

    @Override
    public SysUser querySysUserInfoByUserId(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        List<SysUserRole> sysList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id));
        if (CollectionUtil.isNotEmpty(sysList) && sysList.size() != 0){
            List<Long> roleIdList = sysList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    //先删除管理员与角色关系记录
    //添加新的管理员与角色关系记录
    //修改管理员信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateSysUserInfo(SysUser sysUser) {
        Long userId = sysUser.getUserId();
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        // 添加用户角色关系
        List<Long> roleIdList = sysUser.getRoleIdList();
        if(CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size()>0){
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            roleIdList.forEach(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);

                sysUserRoleList.add(sysUserRole);
            });
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        String newpassword = sysUser.getPassword();
        if (StringUtils.hasText(newpassword)){
            //有值，需要修改密码
            sysUser.setPassword(bCryptPasswordEncoder.encode(newpassword));
        }

        return sysUserMapper.updateById(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeUserListById(List<Long> userIds) {
        //    1.批量/单个删除管理员与角色的关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId, userIds));
        //    2.批量/单个删除管理员
        return sysUserMapper.deleteBatchIds(userIds) == userIds.size();
    }

}
